﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SpringStudio.Common;
using SpringStudio.DAL.PaginationHandler;
using Sdepci.InfoCode.BLL;

namespace Sdepci.InfoCode.Web.Includes
{
    public partial class Pagination : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        #region 属性定义：输入参数

        private string dataBaseConnectionString = ConnectionString.Default;
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string DataBaseConnectionString
        {
            set { this.dataBaseConnectionString = value; }
            get { return this.dataBaseConnectionString; }
        }

        private string _tableName = string.Empty;
        /// <summary>
        /// 数据表名（必选）
        /// </summary>
        public string TableName
        {
            set { this._tableName = value; }
            get { return this._tableName; }
        }

        private List<string> _primaryKeys = new List<string>();
        /// <summary>
        /// 主键（必选）
        /// </summary>
        public List<string> PrimaryKeys
        {
            set { this._primaryKeys = value; }
            get { return this._primaryKeys; }
        }

        private List<PaginationOrderField> _orderFields = new List<PaginationOrderField>();
        /// <summary>
        /// 排序字段
        /// </summary>
        public List<PaginationOrderField> OrderFields
        {
            set { this._orderFields = value; }
            get { return this._orderFields; }
        }

        private List<string> _columns = new List<string>();
        /// <summary>
        /// 返回的列（默认返回所有列）
        /// </summary>
        public List<string> Columns
        {
            set { this._columns = value; }
            get { return this._columns; }
        }

        private string _selectCondition = string.Empty;
        /// <summary>
        /// 查询条件（可以带参数）
        /// </summary>
        public string SelectCondition
        {
            set { this._selectCondition = value; }
            get { return this._selectCondition; }
        }

        private List<PaginationSqlParameter> _sqlParameters = new List<PaginationSqlParameter>();
        /// <summary>
        /// 查询参数（只读，可选，通常当定义查询条件时定义）
        /// </summary>
        public List<PaginationSqlParameter> SqlParameters
        {
            set { this._sqlParameters = value; }
            get { return this._sqlParameters; }
        }

        private int _pageSize = 10;
        /// <summary>
        /// 页面大小（可选，默认每页返回10条记录）
        /// </summary>
        public int PageSize
        {
            set { this._pageSize = value; }
            get { return this._pageSize; }
        }

        private int _pageIndex = 0;
        /// <summary>
        /// 当前页（只读）
        /// </summary>
        public int PageIndex
        {
            get
            {
                if (this._pageIndex == 0)
                {
                    // 初始化当前页
                    if (this.Request.QueryString["PageIndex"] != null && this.Request.QueryString["PageIndex"].Trim().Length > 0)
                    {
                        this._pageIndex = int.Parse(this.Request.QueryString["PageIndex"].Trim());

                        if (this.PageCount >= 1 && this._pageIndex < 1)
                        {
                            this._pageIndex = 1;
                        }
                        else if (this._pageIndex > this.PageCount)
                        {
                            this._pageIndex = this.PageCount;
                        }
                    }
                    else
                    {
                        this._pageIndex = 1;
                    }
                }

                return this._pageIndex;
            }
        }

        #endregion

        #region 属性定义：输出参数

        private DataSet _totalDataSet = null;
        /// <summary>
        /// 符合条件的所有记录集（只读）
        /// </summary>
        public DataSet TotalDataSet
        {
            get
            {
                if (this._totalDataSet == null)
                {
                    // 检查必选参数
                    if (this.TableName.Length == 0)
                    {
                        throw new ArgumentNullException("TableName", "数据表名不得为空！");
                    }

                    if (this.PrimaryKeys.Count < 1)
                    {
                        throw new ArgumentNullException("PrimaryKeys", "主键字段不得为空！");
                    }

                    this._totalDataSet = PaginationAnalysis.GetTotalDataSet(this.DataBaseConnectionString, this.TableName, this.PrimaryKeys, this.OrderFields,
                        this.Columns, this.SelectCondition, this.SqlParameters);
                }

                return this._totalDataSet;
            }
        }

        private DataSet _pageDataSet = null;
        /// <summary>
        /// 当前页数据集（只读）
        /// </summary>
        public DataSet PageDataSet
        {
            get
            {
                if (this._pageDataSet == null)
                {
                    // 检查必选参数
                    if (this.TableName.Length == 0)
                    {
                        throw new ArgumentNullException("TableName", "数据表名不得为空！");
                    }

                    if (this.PrimaryKeys.Count < 1)
                    {
                        throw new ArgumentNullException("PrimaryKeys", "主键字段不得为空！");
                    }

                    this._pageDataSet = PaginationAnalysis.GetDataSet(this.DataBaseConnectionString, this.TableName, this.PrimaryKeys, this.OrderFields,
                        this.Columns, this.SelectCondition, this.SqlParameters, this.PageSize, this.PageIndex, this.RecordCount);
                }

                return this._pageDataSet;
            }
        }

        private DataSet _numberPageDataSet = null;
        /// <summary>
        /// 带有编号字段的当前页数据集（只读）
        /// </summary>
        public DataSet NumberPageDataSet
        {
            get
            {
                if (this._numberPageDataSet == null)
                {
                    this._numberPageDataSet = PaginationAnalysis.GetNumberDataSet(this.PageDataSet, this.PageSize, this.PageIndex);
                }

                return this._numberPageDataSet;
            }
        }

        private int _recordCount = -1;
        /// <summary>
        /// 符合条件的记录总数（只读）
        /// </summary>
        public int RecordCount
        {
            get
            {
                if (this._recordCount == -1)
                {
                    // 检查必选参数
                    if (this.TableName.Length == 0)
                    {
                        throw new ArgumentNullException("TableName", "数据表名不得为空！");
                    }

                    if (this.PrimaryKeys.Count < 1)
                    {
                        throw new ArgumentNullException("PrimaryKeys", "主键字段不得为空！");
                    }

                    this._recordCount = PaginationAnalysis.GetRecordCount(this.DataBaseConnectionString, this.TableName, this.SelectCondition, this.SqlParameters);
                }

                return this._recordCount;
            }
        }

        private int _pageCount = -1;
        /// <summary>
        /// 符合条件的总页数（只读）
        /// </summary>
        public int PageCount
        {
            get
            {
                if (this._pageCount == -1)
                {
                    this._pageCount = int.Parse(Math.Ceiling((double)this.RecordCount / this.PageSize).ToString());
                }

                return this._pageCount;
            }
        }

        private string _urlAddOn = string.Empty;
        /// <summary>
        /// 导航链接后附加的Url参数
        /// </summary>
        public string UrlAddOn
        {
            set { this._urlAddOn = value; }
            get { return this._urlAddOn; }
        }

        #endregion

        #region 控件方法

        /// <summary>
        /// 初始化分页控件HTML代码
        /// </summary>
        public void InitHtml()
        {
            this.lblRecordCount.Text = this.RecordCount.ToString();
            this.lblPageIndex.Text = this.PageIndex.ToString();
            this.lblPageCount.Text = this.PageCount.ToString();
            this.SetRecordCount.InnerHtml = this.SetRecordCount.InnerHtml.Replace("{RecordCount}", this.RecordCount.ToString());
            this.SetPageCount.InnerHtml = this.SetPageCount.InnerHtml.Replace("{PageCount}", this.PageCount.ToString());
            this.SetUrlAddOn.InnerHtml = this.SetUrlAddOn.InnerHtml.Replace("{UrlAddOn}", this.UrlAddOn);

            string url = this.Request.Url.PathAndQuery;
            string begin, end, previous, next;

            if (Regex.IsMatch(url, "PageIndex=[0-9]+", RegexOptions.IgnoreCase))
            {
                begin = Regex.Replace(url, "PageIndex=[0-9]+", "PageIndex=1", RegexOptions.IgnoreCase);
                end = Regex.Replace(url, "PageIndex=[0-9]+", "PageIndex=" + this.PageCount.ToString(), RegexOptions.IgnoreCase);
                previous = Regex.Replace(url, "PageIndex=[0-9]+", "PageIndex=" + (this.PageIndex - 1).ToString(), RegexOptions.IgnoreCase);
                next = Regex.Replace(url, "PageIndex=[0-9]+", "PageIndex=" + (this.PageIndex + 1).ToString(), RegexOptions.IgnoreCase);
            }
            else
            {
                if (url.IndexOf("?") > -1)
                {
                    begin = url + "&PageIndex=1";
                    end = url + "&PageIndex=" + this.PageCount.ToString();
                    previous = url + "&PageIndex=" + (this.PageIndex - 1).ToString();
                    next = url + "&PageIndex=" + (this.PageIndex + 1).ToString();
                }
                else
                {
                    begin = url + "?PageIndex=1";
                    end = url + "?PageIndex=" + this.PageCount.ToString();
                    previous = url + "?PageIndex=" + (this.PageIndex - 1).ToString();
                    next = url + "?PageIndex=" + (this.PageIndex + 1).ToString();
                }
            }

            // 上一页
            if (this.PageIndex > 1)
            {
                this.lblBegin.Text = "<a href=\"" + begin + this.UrlAddOn + "\">首页</a>";
                this.lblPrevious.Text = "<a href=\"" + previous + this.UrlAddOn + "\">上一页</a>";
            }
            else
            {
                this.lblBegin.Text = "";
                this.lblPrevious.Text = "";
            }

            // 下一页
            if (this.PageIndex < this.PageCount)
            {
                this.lblNext.Text = "<a href=\"" + next + this.UrlAddOn + "\">下一页</a>";
                this.lblEnd.Text = "<a href=\"" + end + this.UrlAddOn + "\">尾页</a>";
            }
            else
            {
                this.lblNext.Text = "";
                this.lblEnd.Text = "";
            }
        }

        #endregion
    }
}